package com.wsc.wisdomchina.activitity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.activitity.baseactivity.BaseActivity;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.fragment.ExamFragment;
import com.wsc.wisdomchina.javaBean.QuestionBean;
import com.wsc.wisdomchina.javaBean.RespObj;
import com.wsc.wisdomchina.presenter.ContributorPresenter;
import com.wsc.wisdomchina.welfare.activity.ResultActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/9/27.
 */

public class ExaminationActivity extends BaseActivity implements View.OnClickListener, ContributorView {
    private final String FLAG_LIST = "flag_list";
    private final String FLAG_COMMIT = "flag_commit";
    private TextView tv_headtitle;
    private ImageView regist_back;
    private ViewPager mViewPager;
    private ContributorPresenter contributorPresenter;
    private List<QuestionBean> mData;
    private List<ExamFragment> mList;
    private String pmcid = "";
    private FragmentManager mFm;
    private CountDownTimer mTimer;
    private TextView mFinishTv;
    private TextView mCountTv;
    private Button mCommit;
    private String[] answersArr;
    private int mCurrentIndex;
    private String checkId = "";
    private String memId = "";
    private String streetId = "";
    private String mName = "";
    private String mTime = "";
    private Context mContext;
    private int mLimitTime = 0;
    private String desc = "";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.examination_activity_layout);
        mContext = this;
        Intent intent = getIntent();
        if (null == intent) {
            showToast("数据为空");
            finish();
        }
        checkId = intent.getStringExtra("checkId");
        memId = intent.getStringExtra("memId");
        streetId = intent.getStringExtra("streetId");
        pmcid = intent.getStringExtra("pmcId");
        mName = intent.getStringExtra("mName");
        mTime = intent.getStringExtra("time");
        try {
            mLimitTime = Integer.parseInt(mTime);
        } catch (Exception e) {
            showToast("考试时间异常");
            finish();
            e.printStackTrace();
        }
        if(TextUtils.isEmpty(pmcid)){
            showToast("试题编号异常");
            finish();
        }
        initView();
    }

    private void initView() {
        mFm = getSupportFragmentManager();
        tv_headtitle = (TextView) findViewById(R.id.tv_headtitle);
        tv_headtitle.setText("在线答题");
        tv_headtitle.requestFocus();
        tv_headtitle.setFocusable(true);
        tv_headtitle.setFocusableInTouchMode(true);
        mFinishTv = (TextView) findViewById(R.id.tv_finish);
        mCountTv = (TextView) findViewById(R.id.tv_count);
        mCommit = (Button) findViewById(R.id.btn_commit);
        mCommit.setOnClickListener(this);
        mViewPager = (ViewPager) findViewById(R.id.main_viewpager);
        //创建 Adapter
        // MyPagerAdapter pagerAdapter=new MyPagerAdapter(views,titles);

        //添加适配器
        // mViewPager.setAdapter(pagerAdapter);
        regist_back = (ImageView) findViewById(R.id.regist_back);
        regist_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        loadData();

    }

    private void loadData() {
        mCommit.setEnabled(false);
        contributorPresenter = new ContributorPresenter(this, this);
        contributorPresenter.getExercises(pmcid, FLAG_LIST);
    }

    @Override
    public void onLoadContributorStart(String flag) {

    }

    @Override
    public void onLoadContributorComplete(String flag) {
    }

    @Override
    public void onLoadContributorError(String error, String flag) {
    }

    public void updateAnswer( String id,String answer) {
        if (null != answersArr) {
            if (mCurrentIndex >= 0 && mCurrentIndex < answersArr.length) {
                answersArr[mCurrentIndex] = id + "-" + answer;
            }
        }
    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            if (flag.equals(FLAG_LIST)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    mData = JsonTools.jsonStringToList(jsonMessage, QuestionBean.class);
                    mList = new ArrayList<>();
                    if (mData != null && mData.size() > 0) {
                        answersArr = new String[mData.size()];
                        for(int i=0;i<mData.size();i++){
                            answersArr[i] = mData.get(i).getId()+"-" + "null";
                        }
                        mCountTv.setText(mData.size() + "");
                        for (int i = 0; i < mData.size(); i++) {
                            ExamFragment f = new ExamFragment();
                            f.setData(mData.get(i));
                            mList.add(f);
                        }
                        //创建 Adapter
                        AdapterFragment pagerAdapter = new AdapterFragment(mFm, mList);
                        //添加适配器
                        mViewPager.setAdapter(pagerAdapter);
                        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                            @Override
                            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                            }

                            @Override
                            public void onPageSelected(int position) {
                                mCurrentIndex = position;
                                mFinishTv.setText((position + 1) + "");
                                if(position == mList.size()-1){
                                  mCommit.setEnabled(true);
                                }
                            }

                            @Override
                            public void onPageScrollStateChanged(int state) {

                            }
                        });
                        startCountDownTime(mLimitTime * 60);
                    }
                }
            }else if(flag.equals(FLAG_COMMIT)){
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                if (code.equals("200")) {
                    Intent intent = new Intent(mContext,ExamResultActivity.class);
                    intent.putExtra("desc",desc);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(mContext,"提交失败",Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void nextQuestion(){
        if (null != answersArr) {
            if (mCurrentIndex >= 0 && mCurrentIndex < answersArr.length -1) {
                mCurrentIndex ++;
                mViewPager.setCurrentItem(mCurrentIndex);
            }
            if(mCurrentIndex == answersArr.length -1){
                mCommit.setEnabled(true);
            }
        }
    }

    private void startCountDownTime(long time) {
        desc = "";
        /**
         * 最简单的倒计时类，实现了官方的CountDownTimer类（没有特殊要求的话可以使用）
         * 即使退出activity，倒计时还能进行，因为是创建了后台的线程。
         * 有onTick，onFinsh、cancel和start方法
         */
        mTimer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                //每隔countDownInterval秒会回调一次onTick()方法
                // Log.d(TAG, "onTick  " + millisUntilFinished / 1000);
                long leftSeconds = millisUntilFinished / 1000;
                long minutes = leftSeconds / 60;
                long seconds = leftSeconds % 60;
                tv_headtitle.setText("倒计时：" + minutes + ":" + seconds);
            }

            @Override
            public void onFinish() {
                //Log.d(TAG, "onFinish -- 倒计时结束");
                desc = "答题时间已到，系统自动为您提交";
                commit();
                stopTimer();
                finish();
            }
        };
        mTimer.start();// 开始计时
        //timer.cancel(); // 取消
    }

    private void stopTimer() {
        if (null != mTimer) {
            mTimer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btn_commit:
                desc = "请耐心等待考核";
                commit();
                break;
        }

    }

    private void commit() {
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        for(int i = 0;i<answersArr.length;i++){
            String text = answersArr[i];
             String[] str = text.split("-");
            String second = str[1];
            if(TextUtils.isEmpty(second) || "null".equals(second)){
                second = "\"\"";
            }
            if(i == answersArr.length-1){
                sb.append(str[0]).append(":").append(second);
            }else{
                sb.append(str[0]).append(":").append(second).append(",");
            }
        }
        sb.append("}");
         contributorPresenter.postSubmitCheckRecord(checkId,memId,streetId,sb.toString(),mName,FLAG_COMMIT);
    }


    class AdapterFragment extends FragmentPagerAdapter {
        private List<ExamFragment> mFragments;

        public AdapterFragment(FragmentManager fm, List<ExamFragment> mFragments) {
            super(fm);
            this.mFragments = mFragments;
        }

        @Override
        public Fragment getItem(int position) {//必须实现
            return mFragments.get(position);
        }

        @Override
        public int getCount() {//必须实现
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {//选择性实现
            return mFragments.get(position).getClass().getSimpleName();
        }
    }


}
